﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using System.Collections.Generic;
using Telerik.Web.UI;
using System.Text;

namespace Runda.CMS.Portal.SalesManage
{
    public partial class MaintainInstrument : BasePage
    {
        public string SortString
        {
            get
            {
                if (ViewState["SortString"] == null)
                {
                    ViewState["SortString"] = "StandardInstrumentName";
                }

                return ViewState["SortString"].ToString();
            }
            set { ViewState["SortString"] = value; }
        }

        public string SortString1
        {
            get
            {
                if (ViewState["SortString1"] == null)
                {
                    ViewState["SortString1"] = "StandardInstrumentName";
                }

                return ViewState["SortString1"].ToString();
            }
            set { ViewState["SortString1"] = value; }
        }

        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                DataTable dt = new BudgetBll().Companylist(base.CurrentUserID.ToString());
                ddlCompany.DataSource = dt;
                ddlCompany.DataTextField = "Departmentname";
                ddlCompany.DataValueField = "Departmentname";
                ddlCompany.DataBind();
                ddlCompany.Items.Add(new ListItem("--不限--", ""));
                ddlCompany.SelectedValue = "";

                dt = new BudgetBll().Companylist(base.CurrentUserID.ToString());
                
                LoadRadTree("");
                BindGrid(1);
               
                
            }
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid(1);
            
        }

        protected void btnSearch_Click1(object sender, EventArgs e)
        {
            if (txtInstrumentName1.Text.Trim() != "" || txtInstrumentCode1.Text.Trim() != "" || txtInstrumentStd1.Text.Trim()!="")
            {
                BindGrid1(1);
            }
        }


        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (hidinstrumentID.Value == "")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "保存提示！", "alert('请先选择存货明细记录！');", true);
                return;
            
            }

            Guid ID = new Guid(hidinstrumentID.Value);
            SystemBll bll = new SystemBll();
            BGInstrumentEntity instrmentEntity = bll.Get<BGInstrumentEntity>(ID);
            if (instrmentEntity != null)
            {
                instrmentEntity.StandardInstrumentCode = txtCode.Text.Trim();
                instrmentEntity.StandardInstrumentName = txtName.Text.Trim();
                instrmentEntity.StandardInstrumentStd = txtStd.Text.Trim();
                instrmentEntity.CheckStatus ="1";
                instrmentEntity.Checktime = System.DateTime.Now;
                instrmentEntity.Updatedman = CurrentUserEntity.UserName;


                if (Text1.Value != "")
                {
                    Guid categoryID = new Guid(Text1.Value);
                    CtrtInstrumentCategoryEntity categoryEntity = bll.Get<CtrtInstrumentCategoryEntity>(categoryID);
                    if (categoryEntity != null)
                    {
                        instrmentEntity.CategoryCode = categoryEntity.categoryCode;
                    }
                }
                bll.InsertOrUpdate(instrmentEntity);
                new BillBll().updateBillCategoryCode(instrmentEntity.CompanyName, instrmentEntity.InstrumentCode, instrmentEntity.CategoryCode);
                hidinstrumentID.Value = "";
                ClientScript.RegisterStartupScript(this.GetType(), "保存提示！", "alert('保存成功！');", true);
            }
            

            //BindGrid(AspNetPager1.CurrentPageIndex);
        }

        protected void gridAccessoryList1_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            if (e.CommandName.ToLower() == "reference")
            {
                Label txtStandardInstrumentName = e.Item.FindControl("txtStandardInstrumentName") as Label;
                txtName.Text = txtStandardInstrumentName.Text;
               
            }
            //BindGrid(AspNetPager1.CurrentPageIndex);
            //Calculate();
        }

        protected void gridAccessoryList_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            if (e.CommandName.ToLower() == "cancel")
            {
                hidinstrumentID.Value = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["instrumentID"].ToString();
                Guid ID = new Guid(hidinstrumentID.Value);
                SystemBll bll = new SystemBll();
                BGInstrumentEntity instrmentEntity = bll.Get<BGInstrumentEntity>(ID);
                if (instrmentEntity != null)
                {
                    instrmentEntity.StandardInstrumentCode = instrmentEntity.InstrumentCode;
                    instrmentEntity.StandardInstrumentName = instrmentEntity.InstrumentName;
                    instrmentEntity.StandardInstrumentStd = instrmentEntity.InstrumentStd;
                    instrmentEntity.Checktime = System.DateTime.Now;
                    instrmentEntity.Updatedman = CurrentUserEntity.UserName;
                    bll.InsertOrUpdate(instrmentEntity);
                    ClientScript.RegisterStartupScript(this.GetType(), "保存提示！", "alert('成功以当前公司存货建标！');", true);
                }
            }
            BindGrid(AspNetPager1.CurrentPageIndex);
            //Calculate();
        }

        protected void gridAccessoryList_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e)
        {
            if (e.Item.ItemType == Telerik.WebControls.GridItemType.Item || e.Item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
            {
                LinkButton lnkbtnDelete = e.Item.FindControl("lnkbtnDelete") as LinkButton;
                if (lnkbtnDelete != null)
                {
                    //DataRowView dv = e.Item.DataItem as DataRowView;
                    //if (new BudgetBll().GetBudgetSubmitStatus(ddlBudgetYear.SelectedValue.ToString(), dv["ProductManager"].ToString()) > 0 || !base.CheckUserHasFuction(1, "Func10011"))
                    //{ lnkbtnDelete.Visible = false; }

                    //lnkEdit.NavigateUrl = "~/Budget/SalesbudgetDetail.aspx?AssistID=" + dv["AssistID"].ToString();
                    lnkbtnDelete.OnClientClick = "return OnDelConfirm();";
                }
            }
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
        }

        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            BindGrid1(AspNetPager2.CurrentPageIndex);
        }

        protected void btnRefersh_Click(object sender, EventArgs e)
        {
            //BindGrid(AspNetPager1.CurrentPageIndex);
            //Calculate();
        }

        private void BindGrid1(int pageindex)
        {
            string sb = getWhereClause1();
            int RecordCount = 0;
            DataTable dt = new BillBll().QueryInstrumentList(sb, SortString1, AspNetPager2.PageSize, pageindex, out RecordCount);//new BillBll().QueryInstrumentList(sb, "StandardInstrumentName");

            AspNetPager2.RecordCount = RecordCount;
            gridAccessoryList1.DataSource = dt;
            gridAccessoryList1.DataBind();
        }
        private void BindGrid(int pageindex)
        {
            string sb = getWhereClause();

            int RecordCount = 0;
            DataTable dt = new BillBll().QueryInstrumentList(sb, SortString, AspNetPager1.PageSize, pageindex, out RecordCount);

            AspNetPager1.RecordCount = RecordCount;
            gridAccessoryList.DataSource = dt;
            gridAccessoryList.DataBind();
        }

        protected void gridAccessoryList_SortCommand(object source, Telerik.WebControls.GridSortCommandEventArgs e)
        {
            string OrderBy = e.SortExpression + " " + (e.NewSortOrder == Telerik.WebControls.GridSortOrder.Ascending ? "asc" : "desc");
            SortString = OrderBy;
            BindGrid(AspNetPager1.CurrentPageIndex);
            

        }

        protected void gridAccessoryList1_SortCommand(object source, Telerik.WebControls.GridSortCommandEventArgs e)
        {
            string OrderBy = e.SortExpression + " " + (e.NewSortOrder == Telerik.WebControls.GridSortOrder.Ascending ? "asc" : "desc");
            SortString = OrderBy;
            BindGrid1(AspNetPager2.CurrentPageIndex);


        }

        private string getWhereClause()
        { 
            StringBuilder sb = new StringBuilder();

             if (ddlCompany.SelectedValue != "")
            {
                sb.Append(" and CompanyName ='" + ddlCompany.SelectedValue.ToString() + "'");
            }
            if (ddlAdjust.SelectedValue != "")
            {
                sb.Append(" and CheckStatus='" + ddlAdjust.SelectedValue+"'");
            }

            if (txtInstrumentName.Text.Trim() != "")
            {
                sb.Append(" and a.InstrumentName  like '%").Append(txtInstrumentName.Text.Trim()).Append("%'");
            }

            if (txtCategoryCode.Text.Trim() != "")
            {
                sb.Append(" and a.CategoryCode  like '%").Append(txtCategoryCode.Text.Trim()).Append("%'");
            }
            
            return sb.ToString();
        }

        private string getWhereClause1()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(" and checkStatus ='1'");


            if (txtInstrumentName1.Text.Trim() != "")
            {
                sb.Append(" and a.StandardInstrumentName  like '%").Append(txtInstrumentName1.Text.Trim()).Append("%'");
            }

            if (txtInstrumentStd1.Text.Trim() != "")
            {
                sb.Append(" and a.StandardInstrumentStd  like '%").Append(txtInstrumentStd1.Text.Trim()).Append("%'");
            }

            if (txtInstrumentCode1.Text.Trim() != "")
            {
                sb.Append(" and a.StandardInstrumentCode  like '").Append(txtInstrumentCode1.Text.Trim()).Append("%'");
            }


            return sb.ToString();
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            string Whereclause = getWhereClause();

            BillBll bll = new BillBll();

            DataTable dt = bll.BGInstrument_export(Whereclause);

            Export.Export2Excel(dt, "分公司存货档案信息", Page.Response);

        }

        protected void lnkbtnSubmit_Click(object sender, EventArgs e)
        {

            

        }

        protected void lnkbtnCheck_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();
            //bll.CheckBudget(ddlBudgetYear.SelectedValue.ToString(), base.CurrentUserEntity.UserName);
        }

        private void LoadRadTree(string categoryCode)
        {
            string categoryGUID = "";
            //List<CtrtInstrumentCategoryEntity> categoryEntitys = new CtrtInstrumentCategoryBll().GetAll<CtrtInstrumentCategoryEntity>(" and parentGUID is null", "Order By categoryCode"); 
            DataTable dt = null;
            CtrtInstrumentCategoryBll bll = new CtrtInstrumentCategoryBll();
            dt = bll.GetInstrumentCategory("");//  and SUBSTRING(categorycode,1,2) in('01', '02')


            RadTreeView RadTreeProdType = RadComboBox_ProdType.Items[0].FindControl("RadTreeView_ProdType") as RadTreeView;
            //HtmlInputHidden Hidden_ProdTypeID = Page.FindControl("Text1") as HtmlInputHidden;
            //HtmlInputText txtSelectType = Page.FindControl("txt_SelectType") as HtmlInputText;
            if (RadTreeProdType != null)
            {
                RadTreeProdType.DataFieldID = "categoryGUID";
                RadTreeProdType.DataTextField = "categoryName";
                RadTreeProdType.DataValueField = "categoryGUID";
                RadTreeProdType.DataFieldParentID = "parentGUID";
                RadTreeProdType.DataSource = dt;
                RadTreeProdType.DataBind();
            }
            if (categoryCode != "")
            {
                Text1.Value = categoryCode;
                List<CtrtInstrumentCategoryEntity> categoryEntitys = new CtrtInstrumentCategoryBll().GetAll<CtrtInstrumentCategoryEntity>(" and parentGUID is null", "Order By categoryCode");

                if (categoryEntitys != null && categoryEntitys.Count > 0)
                {
                    categoryGUID = categoryEntitys[0].categoryCode;
                }

                if (categoryGUID != "")
                {
                    txt_SelectType.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;

                    RadComboBox_ProdType.SelectedItem.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                    RadComboBox_ProdType.SelectedItem.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                    RadComboBox_ProdType.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                }
            }

        }

        protected void btnRefershBillInfo_Click(object sender, EventArgs e)
        {

            txtCode.Text = hidinstrumentID.Value;

            if (hidinstrumentID.Value != "")
            {
                Guid ID = new Guid(hidinstrumentID.Value);
                SystemBll bll = new SystemBll();
                BGInstrumentEntity instrmentEntity = bll.Get<BGInstrumentEntity>(ID);
                if (instrmentEntity != null)
                {
                    txtCode.Text = instrmentEntity.StandardInstrumentCode;
                    txtName.Text = instrmentEntity.StandardInstrumentName;
                    txtStd.Text = instrmentEntity.StandardInstrumentStd;

                    txtInstrumentName1.Text = instrmentEntity.StandardInstrumentName; ;

                    List<CtrtInstrumentCategoryEntity> categoryEntitys = new CtrtInstrumentCategoryBll().GetAll<CtrtInstrumentCategoryEntity>(" and categorycode='" + instrmentEntity.CategoryCode+"'");

                    if (categoryEntitys != null && categoryEntitys.Count > 0)
                    {
                        string categoryGUID = categoryEntitys[0].categoryGUID.ToString();
                        Text1.Value = categoryGUID;
                        RadTreeView RadTreeProdType = RadComboBox_ProdType.Items[0].FindControl("RadTreeView_ProdType") as RadTreeView;
                        txt_SelectType.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;

                        RadComboBox_ProdType.SelectedItem.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                        RadComboBox_ProdType.SelectedItem.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                        RadComboBox_ProdType.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                    }
                }

                BindGrid1(1);
            }
        }

        protected void btnReference_Click(object sender, EventArgs e)
        {

            if (hidinstrumentID1.Value != "" && hidinstrumentID.Value != "")
            {
                Guid ID = new Guid(hidinstrumentID1.Value);
                SystemBll bll = new SystemBll();
                BGInstrumentEntity instrmentEntity = bll.Get<BGInstrumentEntity>(ID);
                if (instrmentEntity != null)
                {
                    txtCode.Text = instrmentEntity.StandardInstrumentCode;
                    txtName.Text = instrmentEntity.StandardInstrumentName;
                    txtStd.Text = instrmentEntity.StandardInstrumentStd;

                    List<CtrtInstrumentCategoryEntity> categoryEntitys = new CtrtInstrumentCategoryBll().GetAll<CtrtInstrumentCategoryEntity>(" and categorycode='" + instrmentEntity.CategoryCode+"'");

                    if (categoryEntitys != null && categoryEntitys.Count > 0)
                    {
                        string categoryGUID = categoryEntitys[0].categoryGUID.ToString();
                        Text1.Value = categoryGUID;
                        RadTreeView RadTreeProdType = RadComboBox_ProdType.Items[0].FindControl("RadTreeView_ProdType") as RadTreeView;
                        txt_SelectType.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;

                        RadComboBox_ProdType.SelectedItem.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                        RadComboBox_ProdType.SelectedItem.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                        RadComboBox_ProdType.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                    }
                }
            }
        }

        

    }
}
